<template>
  <el-form ref="formobj" :model="wyform" :rules="rules" label-width="100px">
    <el-form-item label="编号" prop="code">
      <el-input v-model="wyform.code" maxlength="64" placeholder="请输入科室编号"></el-input>
    </el-form-item>
    <el-form-item label="科室名称" prop="name">
      <el-input v-model="wyform.name" maxlength="64" placeholder="请输入科室名称"></el-input>
    </el-form-item>
    <el-form-item label="类别" prop="type">
      <el-input v-model="wyform.type" maxlength="64" placeholder="请输入科室类别"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="save" v-if="props.id">修改</el-button>
      <el-button type="primary" @click="save" v-else>保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, ref,defineEmits } from 'vue'
import { post,get } from '@/util/axios'
import {url} from './api.js'
const wyform = reactive({
  code: '',
  name: '',
  type: ''
})
const emits=defineEmits(['update:show','getTableData'])
const props=defineProps(['id'])

const check=(rule,value,callback,field)=>{
  get(url.check,{field,value,id:props.id},content=>{
    if (content){
      callback()
    }else{
      callback(new Error())
    }
  })

}
const rules = reactive({
  code: [
    { required: true, message: '请输入科室编码', trigger: 'blur' },
    { validator:(rule,value,callback)=>{check(rule,value,callback,'code')},message: "编码已存在"}
  ],
  name: [
    { required: true, message: '请输入科室名称', trigger: 'blur' },
    { validator:(rule,value,callback)=>{check(rule,value,callback,'name')},message: "名称已存在"}
  ],
  type: [
    { required: true, message: '请输入科室类别', trigger: 'blur' }
  ]
})
const formobj = ref()
if (props.id){
  getById()
}

function getById(){
  get(url.getById, {id:props.id}, content => {
        for(const key in wyform){
          if (Object.prototype.hasOwnProperty.hasOwnProperty.call(content,key)){
            wyform[key]=content[key]
          }
        }
    wyform.id=props.id
    console.log(content)
  }, formobj)
}

function save () {
    post(props.id?url.update :url.add, wyform, content => {
      emits('update:show',false),
          emits('getTableData')
    }, formobj)
}
</script>

<style scoped lang="scss">
</style>
